const express = require('express');
const mysql = require('mysql2');

const options = {
    host: 'localhost' ,
    port: 3306 ,
    user: 'root' ,
    password: '' ,
    database: 'kaifamiao'
}

// 根据数据库配置创建数据库连接
const connection = mysql.createConnection( options );
connection.connect(); // 连接到数据库服务器

const router = express.Router();

router.get( '/teacher/list' , (req,resp)=>{
    let sql = 'SELECT * FROM t_teachers' ;

    let handler = function( error , results , fields ){
        if( error ) {
            console.log( '查询失败' );
            throw error ;
        }
        // '/views/teacher/list.njk'
        let view = 'teacher/list' ;
        let data = {
            teachers: results
        }
        resp.render( view , data );
    }

    // 从数据库中查询教师数据
    connection.query( sql , handler );
});

router.get( '/teacher/remove/:id' , (req,resp)=>{
    // 获取路由参数
    let id = req.params.id ;
    let sql = 'DELETE FROM t_teachers WHERE id = ' + id ;
    let handler = (error,results,fields)=>{
        if( error ){
            console.log( '删除失败' );
            throw error ;
        }
        console.log( results );
        // 删除成后重新返回到列表
        resp.redirect( '/teacher/list' );
    }
    connection.query( sql , handler );
});


module.exports = router ;